from flask import flash, Blueprint, render_template, request, jsonify, redirect, url_for, send_from_directory
from app.config import create_db_connection
import datetime
import os

outbound_order_list_bp = Blueprint('outbound_order_list', __name__)

@outbound_order_list_bp.route('/outbound_order_list')
def outbound_order_list():
    conn, cursor = create_db_connection()
    cursor.execute(
        "SELECT ool.id, c.customer_name, ool.enter_time, ool.document_number "
        "FROM outbound_order_list AS ool "
        "JOIN customer_list AS c ON ool.customer_id = c.id"
    )
    outbound_order_lists = cursor.fetchall()
    cursor.close()
    conn.close()

    return render_template('outbound_order/outbound_order_list.html', ware_entries=outbound_order_lists)


@outbound_order_list_bp.route('/data/<path:filename>')
def customer_static(filename):
    # 产品列表的产品图片显示模块
    return send_from_directory('data', filename)


@outbound_order_list_bp.route('/outbound_order_details/<document_number>')
def ware_entry_details(document_number):
    conn, cursor = create_db_connection()
    cursor.execute(
        "SELECT wep.product_id, p.product_name, p.product_model, p.product_color, wep.quantity, p.product_unit, wep.sales_price, p.image_path "
        "FROM outbound_order_info AS wep "
        "JOIN product_list AS p ON wep.product_id = p.id "
        "WHERE wep.document_number = %s",
        (document_number,)
    )
    products = cursor.fetchall()
    # print(products)

    # 查询 outbound_order_attachment 表，获取图片路径
    cursor.execute(
        "SELECT filename FROM outbound_order_attachment WHERE document_number = %s",
        (document_number,)
    )
    attachments = cursor.fetchall()
    cursor.execute("SELECT * FROM outbound_order_list WHERE document_number = %s", (document_number,))
    entry_info = cursor.fetchall()
    customer_id = entry_info[0][1]
    cursor.execute("SELECT * FROM customer_list WHERE id = %s", (customer_id,))
    customer_info = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('outbound_order/outbound_order_info.html', document_number=document_number,
                           products=products,
                           attachments=attachments, entry_info=entry_info, customer_info=customer_info)
